package cn.aliothstar.code;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @作者：玉蘅
 * @项目名称：sever-synchronization
 * @包名：cn.aliothstar.code
 * @文件名称：Three
 * @代码功能：从JSON文件读取
 * @时间：2023/09/25/22:00
 */
public class Three {
    private static int checkCount = 0; //检测次数
    private static final int THREAD_POOL_SIZE = 5; // 线程池大小

    public static void main(String[] args) {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(THREAD_POOL_SIZE);
        executorService.scheduleAtFixedRate(new CheckServersTask(), 0, 10, TimeUnit.SECONDS); // 每隔10秒执行一次任务
    }

    // TODO 检查服务器任务
    private static class CheckServersTask implements Runnable {
        @Override
        public void run() {
            checkCount++; // 增加检测次数
            System.out.println("+++++++++++++++++++++++++++++");
            System.out.println("第 " + checkCount + " 次检查");
            System.out.println("+++++++++++++++++++++++++++++");

            // 从文件里面读取地址
            try (BufferedReader reader = new BufferedReader(new FileReader("resource/sever.json"))) {
                StringBuilder jsonContent = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    jsonContent.append(line);
                }
                JSONArray serverArray = JSON.parseArray(jsonContent.toString());

                for (Object server : serverArray) {
                    String serverName = server.toString();
                    System.out.println("检查服务器: " + serverName);

                    if (isValidIPAddress(serverName)) {
                        System.out.println("这是一个IP地址.");
                        checkServer(serverName, "http://" + serverName);
                        checkServer(serverName, "https://" + serverName);
                    } else if (serverName.startsWith("http://")) {
                        System.out.println("这是一个HTTP地址.");
                        checkServer(serverName, serverName);
                    } else if (serverName.startsWith("https://")) {
                        System.out.println("这是一个HTTPS地址.");
                        checkServer(serverName, serverName);
                    } else {
                        System.out.println("无效的服务器格式: " + serverName);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // TODO 检测是有效的IP地址
        private boolean isValidIPAddress(String address) {
            try {
                InetAddress.getByName(address);
                return true;
            } catch (Exception e) {
                return false;
            }
        }
        // TODO 检查服务器
        private void checkServer(String serverName, String serverURL) {
            try {
                long startTime = System.currentTimeMillis(); // 当前时间毫秒
                URL url = new URL(serverURL); // 服务器的地址
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                int responseCode = connection.getResponseCode();
                long endTime = System.currentTimeMillis();
                long elapsedTime = endTime - startTime;

                System.out.println("服务器: " + serverName);
                System.out.println("响应码: " + responseCode);
                System.out.println("响应时间: " + elapsedTime + " ms");

                if (responseCode == HttpURLConnection.HTTP_OK) {
                    System.out.println("服务器正常.");
                    System.out.println("--------------------------------");
                } else {
                    System.out.println("无法访问服务器.");
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }
}

